package com.distributor;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyAccountActivity extends Activity
{ 
	//Button btnBal,btnInfo,btnFav;
	ListView list;
	TextView tveaderText;
	Handler handler=new Handler();
	MD5Generator md5Generator=new MD5Generator();
	HttpConn httpConn=new HttpConn();
	MyAccountInfo myAccountInfo;
	ProgressDialog pd=null;
	Button btnBack,btnLogOut;
	String[] values = new String[] 
			{
	          "Check Balance","My Info"
	    	};  
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myaccount);
        list=(ListView)findViewById(R.id.lvAccist);
        
        
        
//        btnBal=(Button)findViewById(R.id.btnBal);
//        btnInfo=(Button)findViewById(R.id.btnmyInfo);

//        btnFav=(Button)findViewById(R.id.btnFav);
        btnLogOut=(Button)findViewById(R.id.btnLogout); 
	    btnBack=(Button)findViewById(R.id.btnPrevious);
	    
	    tveaderText=(TextView)findViewById(R.id.tv_headerText);
        tveaderText.setText("My Account");
        MyListAdapter adapter = new MyListAdapter(this, values);
        list.setAdapter(adapter);
	    btnLogOut.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				  new AlertDialog.Builder(MyAccountActivity.this)
				  .setTitle( "Exit Application" )
			      .setMessage( "Are you sure you want to Logout?" )
			      .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
			       {
			           public void onClick(DialogInterface arg0, int arg1) 
			           {
			        	   setResult(2);
			               finish();
			           }

					   public void onClick(View v) 
					   {
						 // TODO Auto-generated method stub
					   }
					   
			        })
			        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
			        {
			            public void onClick(DialogInterface arg0, int arg1)
			            {
			                //do stuff onclick of CANCEL
			            	arg0.dismiss();
			            }

						public void onClick(View v) 
						{
							// TODO Auto-generated method stub
						}
			        }).show();
		  	}
			
		 });  

	    btnBack.setOnClickListener(new OnClickListener() 
	    {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			finish();	
			}
		});
	    list.setOnItemClickListener(new OnItemClickListener()
        {

			public void onItemClick(AdapterView<?> adapterView, View view, int position,
					long id)
			{
				switch (position) 
				{
					case 0:
						 pd=ProgressDialog.show(MyAccountActivity.this,"please wait.",null);
					        pd.setContentView(R.layout.progress);
					        Thread thread=new Thread(getPersonalInfo);
					        thread.start();
						break;
					
					case 1:
						startActivityForResult(new Intent(MyAccountActivity.this,ActivityMyAcc.class),33);
						break; 
				}
				
			}
        });
    /*    btnInfo.setOnClickListener(new OnClickListener()
        {
			
			public void onClick(View arg0)
			{
				// TODO Auto-generated method stub
				startActivityForResult(new Intent(MyAccountActivity.this,ActivityMyAcc.class),33);
				
			}
		});*/

        /*btnBal.setOnClickListener(new OnClickListener()
        {
			
			public void onClick(View v) 
			{
				 pd=ProgressDialog.show(MyAccountActivity.this,"please wait.",null);
			        pd.setContentView(R.layout.progress);
			        Thread thread=new Thread(getPersonalInfo);
			        thread.start();
			}
		});*/
    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
	    if(resultCode==1 && requestCode==33)
	    {
	    	setResult(2);
	        finish();
	    }
	}
	Runnable getPersonalInfo=new Runnable()
	{
		
		public void run() 
		{
			try
			{
				String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+
							 	AppData.getUserInfo().getpublickey() ));
				 String URL=AppData.hostURL+"/WebService/iTopUp/distributorapp.php/GetPersonalInfo/LoginId/"+AppData.getUserInfo().getLoginID()
                         +"/Checksum/"+checksum;
              System.out.println("URL===>\n"+URL);
              String response=httpConn.createHttpConn(URL);
              System.out.println("Response:"+response);
              myAccountInfo=new MyAccountInfo();
              final JSONObject jsonObject=new JSONObject(response);

              if(jsonObject.getString("ResponseCode").equals("000"))
              {
                   
                   
                   if(jsonObject.has("Balance"))
                        myAccountInfo.setBalance(""+Double.parseDouble(jsonObject.getString("Balance"))/100);
                   else
                       myAccountInfo.setBalance("Not Avilable");

                    
                   handler.post(new Runnable()
                   { 
						public void run() 
						{
							// TODO Auto-generated method stub
							Toast.makeText(MyAccountActivity.this,"Your Account Balance is "+myAccountInfo.getBalance(),Toast.LENGTH_SHORT).show();
 
							pd.dismiss();
						}
                   }); 
              }
              else
              {
            	  handler.post(new Runnable()
            	  {
					
					public void run() 
					{
						// TODO Auto-generated method stub
						pd.dismiss();
						try 
						{
							Toast.makeText(MyAccountActivity.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
              }

			}//try
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	};//getpersonalInfo
	 public static class ViewHolder
	 {
			public TextView tvItemName;
			 
     }
	 class MyListAdapter extends ArrayAdapter<String> 
	 {
			
			private final Context context;
			private final String[] values;
			
			LayoutInflater vi ;
		  
			public MyListAdapter(Context context, String[] values)
			{
				super(context, R.layout.row_lv_settings,values);
				
				this.context = context;
				this.values = values; 
				vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			}
 
			public View getView(final int position, View convertView, ViewGroup parent) 
			{
				 View v = convertView;
				 ViewHolder holder = null;
				 
				if (v == null) 
				{
						holder=new ViewHolder();  
						v = vi.inflate(R.layout.row_lv_settings, null); 
						holder.tvItemName=(TextView) v.findViewById(R.id.tvItemName);
						v.setTag(holder); 
					 
				}
				else
					holder=(ViewHolder)v.getTag();
					String name=this.values[position];
					System.out.println(name);
					holder.tvItemName.setText(name);
					  
				 	return v; 
			}
		}	
	 
}
